package com.share.four.netty.runtime;

import com.share.four.netty.runtime.entity.Request;
import com.share.four.netty.runtime.entity.Response;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class ServerHandler extends ChannelHandlerAdapter{

	

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("server channel active...");
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		Request req = (Request)msg;
		System.out.println("server 接收： " + req);
		final Response resp = new Response();
		resp.setId("" + req.getId());
		resp.setName("" + req.getName());
		resp.setResponseMessage("" + req.getRequestMessage());
		final ChannelFuture cf = ctx.writeAndFlush(resp);
		cf.addListeners(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (cf==future) {
					System.out.println("server 发送： " + resp);
				}
			}
		});
		
		try {
			
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

}
